//
//  RequestManager.m
//  liang ping
//
//  Created by lanou on 16/3/11.
//  Copyright © 2016年 孙金龙. All rights reserved.
//

#import "RequestManager.h"

@implementation RequestManager

+ (void)requestWithUrl:(NSString *)urlString  parDic:(NSDictionary *)pardic finish:(Finish)finish error:(Error)error requestType:(Request)requestType
{
    RequestManager *request = [[RequestManager alloc] init];
    [request requestWithUrl:urlString parDic:pardic finish:finish error:error requestType:requestType];
}

// 方法传值
- (void)requestWithUrl:(NSString *)urlString  parDic:(NSDictionary *)parDic finish:(Finish)finish error:(Error)error requestType:(Request)requestType
{
    self.finish = finish;
    self.error = error;
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
   // 判断是否为post请求
    switch (requestType)
    {
        case RequestPost:
            [request setHTTPMethod:@"POST"];
            // 将传进来的字典的参数转化为data
            [request setHTTPBody:[self dicToDataithDic:parDic]];
            break;
         case RequestGte:
            [request setHTTPMethod:@"GET"];
            // 将传进来的字典的参数转化为data
            // [request setHTTPBody:[self dicToDataithDic:parDic]];
        default:
            break;
    }
    
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error)
    {
        if (error)
        {
            self.error(error);
        }
        else
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                 self.finish(data);
            });
        }
        }];
    [task resume];
}

- (NSData *)dicToDataithDic:(NSDictionary *)dic
{
    NSMutableArray *array = [NSMutableArray array];
    // 把字典里的键值对按照key = value 拼接成字符串,最后用&符号链接所有拼接好的字符串
    for (NSString *key in dic)
    {
        NSString *string = [NSString stringWithFormat:@"%@=%@",key,dic[key]];
        [array addObject:string];
    }
    NSString *dataString = [array componentsJoinedByString:@"&"];
    // 返回data
    return [dataString dataUsingEncoding:NSUTF8StringEncoding];
}


@end
